﻿import { convertUTCTimeToLocalTime } from '_commonFn/time.js'
import { getCookie, setCookie, delCookie } from '_commonFn/cookie.js'
import { toLoginPage } from '_projectFn/url'
import store from '_store/store'
import Router from '_router/router'

export function login(urll, state = 'STATE') {
    if (getCookie('Ticket') == '') {
        const url = encodeURI(comPort + urll);
        // const url=encodeURI=('http://gxcdpm.natappfree.cc/dist/index.html');
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9bccc5d90f7d7596&redirect_uri=' + url + '&response_type=code&scope=snsapi_userinfo&state=' + state + '&connect_redirect=1#wechat_redirect';
    } else {
        return true
    }
}

//是否跳转到选择登录页面
export function isLoginChose(url = location.href.split('#')[0]) {
    if (!getCookie('Ticket')) {
        toLoginPage({url})
        return false
    } else {
        return true
    }
}

// 保存登录信息
export const saveLoginInfo = (data, day = 0.1) => {
    // console.log('data', data)
    setCookie('Ticket', data.Ticket, day)
    setCookie('Token', data.Token, day)
    setCookie('UserId', data.LoginUser.UserId, day)
    setCookie('Safetyfactor', data.LoginUser.Safetyfactor, day)
    setCookie('UserName', encodeURI(data.LoginUser.NickName), day)
    setCookie('UserRegDate', convertUTCTimeToLocalTime(data.LoginUser.RegDate), day)
    setCookie('UserHeadImg', data.LoginUser.HeadImg.replace('http:','https:'), day)
    setCookie('Sex', data.LoginUser.Sex == 2 ? 0 
    : data.LoginUser.Sex == 0 ? 2 
    : data.LoginUser.Sex, day)
    store.commit('saveLoginInfo', data)
}

// 执行清除登录用户信息
export const delLoginUserInfo = () => {
    store.commit('clearLoginInfo')
    const arr = ['Ticket', 'Token', 'UserId', 'Safetyfactor', 'UserName', 'UserRegDate', 'UserHeadImg', 'Sex']
    arr.forEach(item => {
        delCookie(item)
    })
}

// 判断是否有用户登录信息，否则进入选择登录页面
export const isLonginChosePage = (ticket = store.state.user.ticket) => {
    if (ticket) {
        Router.push({
            name: 'Login',
            path: `/Login`,
            query: {
                to: encodeURIComponent(returnUrlToLinea())
            }
        })
    }
}

